package org.ztest.thrift;

import java.util.HashMap;
import java.util.Map;

import org.apache.thrift.TException;
import org.ztest.thrift.shared.SharedStruct;
import org.ztest.thrift.tutorial.Calculator;
import org.ztest.thrift.tutorial.InvalidOperation;
import org.ztest.thrift.tutorial.Work;

@RPCProcessor(processor = Calculator.Processor.class, serviceName = "CALCULATOR", iface = Calculator.Iface.class)
public class CalculatorHandler implements org.ztest.thrift.tutorial.Calculator.Iface
{
	private Map<Integer, SharedStruct> log;
	
	public CalculatorHandler()
	{
		log = new HashMap<>();
	}
	
	@Override
	public SharedStruct getStruct(int key) throws TException
	{
		System.out.println("getStruct(" + key + ")");
		return log.get(key);
	}

	@Override
	public void ping() throws TException
	{
		System.out.println("ping()");
	}

	@Override
	public int add(int num1, int num2) throws TException
	{
		System.out.println("add(" + num1 + "," + num2 + ")");
		return num1 + num2;
	}

	@Override
	public int calculate(int logid, Work w) throws InvalidOperation
	{
		System.out.println("calculate(" + logid + ", {" + w.op + "," + w.num1 + "," + w.num2 + ")");
		int val = 0;
		switch (w.op)
		{
		case ADD:
			val = w.num1 + w.num2;
			break;
		case SUBSTRACT:
			val = w.num1 - w.num2;
			break;
		case MULTIPLY:
			val = w.num1 * w.num2;
			break;
		case DIVIDE:
			if (w.num2 == 0)
			{
				InvalidOperation io = new InvalidOperation();
				io.whatOp = w.op.getValue();
				io.why = "Cannot divide by 0";
				throw io;
			}
			val = w.num1 / w.num2;
			break;
		default:
			InvalidOperation io = new InvalidOperation();
			io.whatOp = w.op.getValue();
			io.why = "Unknown operation";
			throw io;
		}
		
		SharedStruct entry = new SharedStruct();
		entry.key = logid;
		entry.value = Integer.toString(val);
		log.put(logid, entry);
		
		return val;
	}

	@Override
	public void zip() throws TException
	{
		System.out.println("zip()");
	}

}
